
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
/* linux 系统关机时, 
1.发送信号 SIGTERM
2.再SIGINT
3.最后在发送SIGKILL (信号9)
 */

void handler_signal(int signal)
{
    char buf[64] = { 0 };
    snprintf(buf, sizeof(buf) - 1, "recv signal=%d", signal);
    printf("%s\n", buf);

    // 关机时, 屏幕涮新太快, 看不到日志, 持久化记录在文件
    char cmd[128] = { 0 };
    snprintf(cmd, sizeof(cmd) - 1, "echo %s >> /home/liuj/signal.log", buf);
    system(cmd);
    printf("%s", cmd);
}

int main()
{
    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_handler = handler_signal;
    act.sa_flags = 0;
    sigaction(SIGTERM, &act, 0);
    sigaction(SIGINT, &act, 0);

    while (1) {
        sleep(60);
    }

    return 0;
}